<template>
  <div class="desensitization-config">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="labelWidth"
      v-loading="formLoading"
      class="config-form"
    >
      <div class="config-card">
        <!-- 操作 -->
        <div class="card-header">
          <div class="header-content">
            <div class="title-section">
              <h3 class="card-title">号码脱敏配置</h3>
            </div>
            <el-button
              type="primary"
              @click="onSubmit"
              v-hasPermi="['crm:module:update']"
              class="save-btn"
            >
              保存
            </el-button>
          </div>
        </div>

        <!-- 表单 -->
        <div class="card-body">
          <el-form-item label="号码脱敏规则设置:" required class="form-item">
            <el-switch
              v-model="formData.status"
              class="custom-switch"
              inline-prompt
              style="--el-switch-on-color: #0052cc; --el-switch-off-color: #dcdfe6"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <div class="config-section">
            <el-form-item label="保留前缀位数:" prop="prefix" class="form-item">
              <div class="input-with-tip">
                <el-input-number
                  v-model="formData.prefix"
                  @change="setExa"
                  :min="preMin"
                  :max="preMax"
                  class="custom-input-number"
                />
              </div>
            </el-form-item>

            <el-form-item label="保留后缀位数:" prop="suffix" class="form-item">
              <div class="input-with-tip">
                <el-input-number
                  v-model="formData.suffix"
                  @change="setExa"
                  :min="sufMin"
                  :max="sufMax"
                  class="custom-input-number"
                />
              </div>
            </el-form-item>

            <el-form-item label="加密符号:" prop="text" class="form-item">
              <el-select
                v-model="formData.text"
                clearable
                placeholder="请选择加密符号"
                @change="setExa"
                class="custom-select"
              >
                <el-option
                  v-for="item in symbolOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="脱敏参考:" class="form-item preview-item">
              <div class="preview-wrapper">
                <span class="preview-text">{{ exaleNum }}</span>
              </div>
            </el-form-item>

            <el-form-item label="指定生效部门" class="form-item">
              <el-tree-select
                ref="treeRef"
                v-model="formData.deptIds"
                :data="deptTreeOptions"
                :props="defaultProps"
                empty-text="加载中，请稍后"
                multiple
                node-key="id"
                show-checkbox
                class="custom-tree-select"
              />
            </el-form-item>

            <el-form-item label="指定员工" class="form-item">
              <el-select
                v-model="formData.userIds"
                multiple
                placeholder="请选择员工"
                class="custom-select"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as mobileApi from '@/api/crm/module/index.ts'

const deptTreeOptions = ref()
const userOptions = ref()
const formLoading = ref(false)
const formData = reactive({
  status: false,
  prefix: 1,
  suffix: 1,
  text: null,
  deptIds: null,
  userIds: null,
  id: null
})
const symbolOptions = [
  {
    name: '*',
    value: '*',
    id: 5
  },
  {
    name: '_',
    value: '_',
    id: 0
  },
  {
    name: '=',
    value: '=',
    id: 1
  },
  {
    name: '$',
    value: '$',
    id: 2
  },
  {
    name: 'A',
    value: 'A',
    id: 3
  },
  {
    name: '^',
    value: '^',
    id: 4
  }
]
const numPhone = '19999999999'
const exaleNum = ref('')
const preMin = ref(1)
const preMax = ref(11)
const sufMin = ref(1)
const sufMax = ref(11)
const formRules = reactive({
  status: [{ required: true, message: '是否启用客户公海不能为空', trigger: 'change' }],
  prefix: [{ required: true, message: '请输入保留前缀位数', trigger: 'blur' }],
  suffix: [{ required: true, message: '请输入保留后缀位数', trigger: 'blur' }],
  text: [{ required: true, message: '请选择加密符号', trigger: 'change' }]
})

// 响应式计算属性
const labelWidth = computed(() => {
  return window.innerWidth <= 768 ? '120px' : '160px'
})

watch(
  () => formData.prefix,
  (val) => {
    sufMax.value = 11 - val
    if (sufMax.value == 11) {
      formData.suffix = 0
    } else {
      if (formData.suffix && formData.suffix > sufMax.value) {
        formData.suffix -= 1
      }
    }
  },
  { immediate: 0, deep: true }
)
watch(
  () => formData.suffix,
  (val) => {
    preMax.value = 11 - val
    if (preMax.value == 11) {
      formData.prefix = 0
    } else {
      if (formData.prefix && formData.prefix > preMax.value) {
        formData.prefix -= 1
      }
    }
  },
  { immediate: 0, deep: true }
)
const replaceString = (str, startKeep, endKeep, ency) => {
  if (str.length !== 11) {
    throw new Error('字符串长度必须为11位')
  }
  const start = str.slice(0, startKeep)
  const end = str.slice(-endKeep)

  const middleLength = str.length - startKeep - endKeep
  const middle = ency.repeat(middleLength)

  return start + middle + end
}
//设置示例号码
const setExa = () => {
  if (formData.prefix && formData.suffix && formData.text) {
    exaleNum.value = replaceString(numPhone, formData.prefix, formData.suffix, formData.text)
  } else {
    exaleNum.value = numPhone
  }
}
// 获得部门列表
const getThree = async () => {
  const deptOptions = await DeptApi.getSimpleDeptList()
  deptTreeOptions.value = handleTree(deptOptions, 'id')
}
// 获得用户列表
const getUserOption = async () => {
  userOptions.value = await UserApi.getSimpleUserList()
}
// 获取配置详情
const getConfig = async () => {
  const data = await mobileApi.getMobileEncrypt()
  if (data) {
    const { id, userIds, text, suffix, status, prefix, deptIds } = data
    Object.assign(formData, { id, userIds, text, suffix, status, prefix, deptIds })
    setExa()
  }
}
onMounted(() => {
  getThree()
  getUserOption()
  getConfig()
})
const formRef = ref()
/**保存*/
const onSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    const data = await mobileApi.saveMobileEncrypt(formData)
    if (data) ElMessage.success('保存成功!')
  } catch {}
}
</script>

<style scoped>
.desensitization-config {
  padding: 16px;
  background: #f8f9fa;
}

/* 表单样式 */
.config-form {
  max-width: 1200px;
  margin: 0 auto;
}

/* 卡片样式 */
.config-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 卡片头部 */
.card-header {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  padding: 20px 24px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title-section {
  flex: 1;
}

.card-title {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.save-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 8px 24px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.save-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 卡片主体 */
.card-body {
  padding: 24px;
}

.form-item {
  margin-bottom: 24px;
}

.form-item :deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  line-height: 1.5;
}

/* 配置区域 */
.config-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

/* 开关样式 */
.custom-switch {
  --el-switch-on-color: #0052cc;
  --el-switch-off-color: #dcdfe6;
}

/* 输入框样式 */
.input-with-tip {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.custom-input-number {
  width: 200px;
}

.custom-input-number :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

.custom-input-number :deep(.el-input-number__decrease),
.custom-input-number :deep(.el-input-number__increase) {
  color: #0052cc;
}

.custom-input-number :deep(.el-input-number__decrease:hover),
.custom-input-number :deep(.el-input-number__increase:hover) {
  background: #f0f7ff;
  color: #003d99;
}

/* 选择器样式 */
.custom-select {
  width: 100%;
}

.custom-select :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 树形选择器样式 */
.custom-tree-select {
  width: 100%;
}

.custom-tree-select :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 预览区域 */
.preview-item {
  margin-bottom: 24px;
}

.preview-wrapper {
  padding: 16px;
  background: #f0f7ff;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-text {
  font-size: 16px;
  font-weight: 600;
  color: #0052cc;
  font-family: 'Courier New', monospace;
  letter-spacing: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .desensitization-config {
    padding: 12px;
  }

  .card-header {
    padding: 16px 20px;
  }

  .header-content {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .save-btn {
    width: 100%;
    max-width: 200px;
  }

  .card-body {
    padding: 16px;
  }

  .config-section {
    padding: 16px;
  }

  .form-item {
    margin-bottom: 20px;
  }

  .custom-input-number {
    width: 100%;
    max-width: 300px;
  }

  .input-with-tip {
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .desensitization-config {
    padding: 8px;
  }

  .card-header {
    padding: 12px 16px;
  }

  .card-title {
    font-size: 16px;
  }

  .card-body {
    padding: 12px;
  }

  .config-section {
    padding: 12px;
  }

  .custom-input-number {
    width: 100%;
  }

  .preview-text {
    font-size: 14px;
    letter-spacing: 1px;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

/* 动画效果 */
.config-card {
  transition: all 0.3s ease;
}

.config-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.preview-wrapper {
  transition: all 0.3s ease;
}

.preview-wrapper:hover {
  background: #e6f4ff;
  border-color: #91caff;
}

/* 主题色变量 */
:root {
  --primary-color: #0052cc;
  --primary-hover: #003d99;
  --primary-light: #f0f7ff;
  --border-color: #e4e7ed;
  --text-color: #303133;
  --bg-color: #f8f9fa;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-form-item__content) {
  flex-wrap: wrap;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-select-dropdown__item.is-selected) {
  color: #0052cc;
  font-weight: 600;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f0f7ff;
}

:deep(.el-tree-select-dropdown .el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f7ff;
  color: #0052cc;
}

:deep(.el-tree-select-dropdown .el-tree-node__content:hover) {
  background-color: #f0f7ff;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}
</style>
